package com.risk.login.service;

import com.risk.login.dto.LoginUserDto;
import com.risk.login.dto.common.LoginConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * @Desc
 * @Date 2018/5/23:下午11:19
 * @uthor yzMa
 * @email 2641007740@qq.com
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LoginUserWService {

    private Logger LOGGER = LoggerFactory.getLogger(LoginUserWService.class);

//    @Autowired
//    private LoginUserRepository loginUserRepository;
    @Autowired
    private RedisTemplate<String,?> redisTemplate;

    private Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(LoginUserDto.class);


    /**
     *
     * @param
     * @return
     * @author:yzMa
     */
    public String writeLoginInfo(LoginUserDto loginUserDto) {
        Assert.notNull(loginUserDto,"writeLoginInfo|loginUserDto should not be null");

        String loginTokenWithoutTimeStamp = loginUserDto.getId()+":"+loginUserDto.getUid();//redis中不存储时间戳，但是写入的cookie和更新redis的传入的值都是带有时间戳的+":"+System.currentTimeMillis();
        loginUserDto.setLoginToken(loginTokenWithoutTimeStamp);

        String redisKey = LoginConstant.REDIS_LOGIN_PREFIX+loginTokenWithoutTimeStamp;
        redisTemplate.execute((RedisCallback<Boolean>) redisConnection -> {
            byte[] data = jackson2JsonRedisSerializer.serialize(loginUserDto);
            return redisConnection.setEx(redisKey.getBytes(), LoginConstant.EXPIRE_TIME_SECONDS, data);
        });
        return loginTokenWithoutTimeStamp;
    }

    /**
     * @description
     * @param
     * @return
     * @author:yzMa
     */
    public boolean updateLoginTokenTTL(String loginToken, Long ttl) {
        Assert.notNull(loginToken,"updateLoginTokenTTL loginToken ttl token 不能为空");

        String[] split = loginToken.split(":");
        if(split == null || split.length!=3){
            LOGGER.info("|updateLoginTokenTTL loginToken={} not illegal",loginToken);
            return false;
        }
        String redisKey =  LoginConstant.REDIS_LOGIN_PREFIX + split[0]+":"+split[1];

        return redisTemplate.execute((RedisCallback<Boolean>) redisConnection -> redisConnection.expire(redisKey.getBytes(), ttl==null?LoginConstant.EXPIRE_TIME_SECONDS:ttl));
    }


    /**
     * @descriptionå
     * @param
     * @return
     * @author:yzMa
     */
    public boolean updateLoginInfo(LoginUserDto loginUserDto) {

        Assert.notNull(loginUserDto,"updateLoginInfo loginUserDto 不能为空");

        String loginToken = loginUserDto.getLoginToken();
        Assert.notNull(loginToken,"updateLoginInfo loginToken 不能为空");

        String[] split = loginToken.split(":");
        if(split == null || split.length!=3){
            LOGGER.info(this.getClass().getSimpleName()+"|updateLoginInfo loginToken={} not illegal",loginToken);
            return false;
        }
        String redisKey =  LoginConstant.REDIS_LOGIN_PREFIX + split[0]+":"+split[1];

        return redisTemplate.execute((RedisCallback<Boolean>) redisConnection -> {
            byte[] data = jackson2JsonRedisSerializer.serialize(loginUserDto);
            return redisConnection.setEx(redisKey.getBytes(), LoginConstant.EXPIRE_TIME_SECONDS, data);//相同会覆盖,不同会新增
        });
    }

}
